var jetpack = require('fs-jetpack');
var fs = require("fs");
var config = require("./cryptConfig")
var crypto = require("crypto");

var excludeDir = Array.isArray(config.excludeDir) ?
  config.excludeDir : [config.excludeDir];
var excludeFile = Array.isArray(config.excludeFile) ?
  config.excludeFile : [config.excludeFile];
var extension = config.extension || "jse";
var algorithm = config.algorithm || "aes192";
var key = config.key || "123456";

var completeCount = 0;

function encrypt(str, algorithm, secret) {
  var cipher = crypto.createCipher(algorithm, secret);
  var enc = cipher.update(str, "utf8", "hex");
  enc += cipher.final("hex")
  return enc;
}

function build(sourcePath, descPath) {
  var stat = jetpack.exists(sourcePath);
  if (stat == "dir") {
    var dirList = jetpack.list(sourcePath);
    dirList.forEach((childDir) => {
      var tmpSourcePath = sourcePath + "/" + childDir;
      var tmpDescPath = descPath + "/" + childDir;
      var stat = jetpack.exists(tmpSourcePath);
      // console.log(excludeFile, childDir)
      if (stat == "dir" && ~excludeDir.indexOf(childDir) == 0) {  // 是目录不在非除目录里
        jetpack.dir(tmpDescPath , { empty: true, mode: '700' }); // 创建目标COPY目录
        build(tmpSourcePath, tmpDescPath);
      } else if (stat == "file") {  //是文件就加密
        if (~excludeFile.indexOf(childDir)) {
          jetpack.copy(tmpSourcePath, tmpDescPath);
        } else if(childDir.endsWith(".js")) {
          var data = jetpack.read(tmpSourcePath);
          var enData = encrypt(data, algorithm, key);
          tmpDescPath = tmpDescPath.replace(/js/, extension);
          jetpack.write(tmpDescPath, enData);
          completeCount ++;
        } else {
          jetpack.copy(tmpSourcePath, tmpDescPath);
        }
      }
    })
  }
}

(function(source, desc) {
  jetpack.remove(desc);
  jetpack.dir(desc, { empty: true, mode: '700' });
  build(source, desc);
  console.log("complete ",completeCount, "file encrypt." )
})(config.source, config.desc)
